import {
  CoolController,
  BaseController,
  CoolCommException,
  CoolTag,
  TagTypes,
} from '@cool-midway/core';
import { Body, Get, Inject, Post } from '@midwayjs/core';
import { UserInfoService } from '../../service/info';
import { UserInfoEntity } from '../../entity/info';
import RsaDecryptService from '../../utils';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { LakalaMerchantEntity } from '../../../payment/entity/lakala_merchant';
import { UserSmsService } from '../../service/sms';



/**
 * 用户信息
 */
@CoolController({
  api: [],
  entity: UserInfoEntity,
})
export class AppUserInfoController extends BaseController {
  @Inject()
  ctx;

  @Inject()
  userInfoService: UserInfoService;


  @InjectEntityModel(LakalaMerchantEntity)
  merchantModel: Repository<LakalaMerchantEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @Inject()
  userSmsService: UserSmsService;

  @Get('/person', { summary: '获取用户信息' })
  async person() {
    return this.ok(await this.userInfoService.person(this.ctx.user.id));
  }

  @Post('/updatePerson', { summary: '更新用户信息' })
  async updatePerson(@Body() body) {
    return this.ok(
      await this.userInfoService.updatePerson(this.ctx.user.id, body)
    );
  }

  @Post('/updatePassword', { summary: '更新用户密码' })
  async updatePassword(
    @Body('password') password: string,
    @Body('code') code: string
  ) {
    await this.userInfoService.updatePassword(this.ctx.user.id, password, code);
    return this.ok();
  }

  @Post('/logoff', { summary: '注销' })
  async logoff() {
    await this.userInfoService.logoff(this.ctx.user.id);
    return this.ok();
  }

  @Post('/bindPhone', { summary: '绑定手机号' })
  async bindPhone(@Body('phone') phone: string, @Body('code') code: string) {
    await this.userInfoService.bindPhone(this.ctx.user.id, phone, code);
    return this.ok();
  }

  @Post('/miniPhone', { summary: '绑定小程序手机号' })
  async miniPhone(@Body() body) {
    const { code, encryptedData, iv } = body;
    return this.ok(
      await this.userInfoService.miniPhone(
        this.ctx.user.id,
        code,
        encryptedData,
        iv
      )
    );
  }

  /* 注册 */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/register', { summary: '注册' })
  async register(
    @Body('phone') phone: string,
    @Body('password') password: string,
    @Body('smsCode') smsCode?: number
  ) {
    /* 校验手机号格式 */
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      throw new CoolCommException('手机号格式不正确');
    }

    // 检验短信验证码
    const check = await this.userSmsService.checkCode(phone, smsCode);

    if (!check) {
      throw new CoolCommException('验证码错误');
    }
    return this.ok(await this.userInfoService.register(phone, password));
  }

  // 创建代理
  @Post('/createAgent', { summary: '创建代理' })
  async createAgent(
    @Body('phone') phone: string,
    @Body('password') password: string,
    @Body('profitRatio') profitRatio: number
  ) {
    return this.ok(
      await this.userInfoService.createAgent(phone, password, profitRatio)
    );
  }

  // 创建商户
  // @Post('/createMerchant', { summary: '创建商户' })
  // async createMerchant(
  //   @Body('phone') phone: string,
  //   @Body('password') password: string,
  //   @Body('profitRatio') profitRatio: number
  // ) {
  //   return this.ok(
  //     await this.userInfoService.createMerchant(phone, password, profitRatio)
  //   );
  // }

  // 获取代理列表，只能获取自己的下级代理
  @Post('/getAgentList', { summary: '获取代理列表' })
  async getAgentList() {
    return this.ok(await this.userInfoService.getAgentList());
  }

  /* 合同 */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/postApplicationConfig', { summary: '进件' })
  async postApplicationConfig(@Body() body) {
    return this.ok(await this.userInfoService.applyContract(body));
  }

  /* 商户入住 */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/settleIn', { summary: '商户入驻' })
  async settleIn(@Body() body) {
    return this.ok(await this.userInfoService.settle(body));
  }

  /* 商户入住 */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/reviewCallback', { summary: '进件回调' })
  async reviewCallback(@Body() body) {
    console.log('获取到进件的回调', body);

    try {
      const decryptService = new RsaDecryptService();
      const result: any = decryptService.decrypt(body.data);


      const _data = JSON.parse(result)


      console.log('解密后的数据:=================', _data);


      // 如果商户入驻成功了
      if (_data?.status === "SUCCESS") {
        const _merchantInfo: any = await this.merchantModel.findOneBy({
          merchantNo: _data.customerNo,
        })

        console.log('_merchantInfo_merchantInfo_merchantInfo_merchantInfo', _merchantInfo);



        await this.userInfoEntity.update(
          { id: _merchantInfo?.userId as number },
          {
            merchantNo: _data.externalCustomerNo,
            terminalNo: _data.termNos,
          }
        );

        // 更新merchantModel
        await this.merchantModel.update(
          { merchantNo: _data.customerNo },
          {
            status: 1,
          }
        );
      }

    } catch (error) {
      console.error('解密错误:', error.message);
    }

    // console.log('decryptService', decryptService);

    /* 正常收到推送请返回200 */
    return this.ok();
  }

  // 
}
